package org.sgy.mall.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.sgy.mall.dao.impl.UserDaoImpl;
import org.sgy.mall.model.User;
import org.sgy.mall.utils.PasswordUtil;

public class LoginServlet extends HttpServlet {

	public LoginServlet() {
	}

	@Override
	public void init() throws ServletException {
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("login servlet");
		HttpSession session = request.getSession();
		ServletContext application = request.getServletContext();
		// 获取登录参数
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("txtUser");
		String pwd = request.getParameter("txtPassword");
		String loginInfo = "";

		// 登录验证,从数据库中验证账号密码
		UserDaoImpl userdao = new UserDaoImpl();
		String encryPwd = PasswordUtil.encryPassword(pwd);
		boolean isLogin = userdao.login(name, encryPwd);
		if (!isLogin) {
			response.getWriter().println("用户名密码错误");
			return;
		}

		// 把用户信息存储到session中
		User user = new User();
		user.setUserName(name);
		user.setPassword(pwd);
		session.setAttribute("user", user);
		response.addCookie(new Cookie("userName", name));
		response.addCookie(new Cookie("password", pwd));
		response.sendRedirect("./index.jsp");

		// 统计在线用户
		HashMap<String, User> userMap = (HashMap<String, User>) application.getAttribute("userMap");
		if (userMap == null) {
			userMap = new HashMap<String, User>();
		}
		userMap.put(name, user);
		application.setAttribute("userMap", userMap);

		response.getWriter().println(loginInfo);
	}

}
